package com.clothing.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.clothing.entity.User;
import com.clothing.entity.WxApp;
import com.clothing.service.UserService;
import com.clothing.service.WxAppService;
import com.clothing.utils.AjaxMsg;
import com.clothing.utils.MathUtils;
import com.clothing.utils.Utils;
import com.clothing.utils.WebUtils;
import com.clothing.utils.WeixinUtils;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

/**
 * @ClassName: WxAppController 
 * @Description: TODO(Controller-微信) 
 * @author Charles.Tao 
 * @date 2017年9月11日 上午10:32:21 
 * @version 1.0
 */
@RequestMapping("/app/wx")
@Controller("wxAppController")
public class WxAppController extends BaseController
{
    @Autowired
    private WxAppService wxAppService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CacheManager cacheManager;
    
    /**
     * @Title: submit 
     * @Description: TODO(授权) 
     * @param @param code
     * @param @param nickname
     * @param @param sex
     * @param @param headImgUrl
     * @param @param session
     * @param @param request
     * @param @return 设定文件 
     * @return String 返回类型 
     * @throws
     */
    @RequestMapping(value = "/authorization", method = RequestMethod.POST)
    @ResponseBody
    public String submit(String code, String nickname, Integer sex, String headImgUrl, HttpServletRequest request)
    {
        if (Utils.isEmpty(code))
        {
            return getParameterErrorMsg();
        }
        
        WxApp wxApp = wxAppService.find(1L);
        JSONObject jo = WeixinUtils.jscodeToSession(wxApp.getAppId(), wxApp.getAppSecret(), code);
        
        if (null == jo)
        {
            return getParameterErrorMsg();
        }
        
        String openid = jo.getString("openid");
        
        if (Utils.isEmpty(openid))
        {
            return getParameterErrorMsg();
        }
        
        User user = userService.findByOpenid(openid);
        String ip = WebUtils.getRemoteIP(request);
        
        if (null == user)
        {
            user = new User();
            user.setOpenid(openid);
            user.setNickname(nickname);
            user.setSex(sex);
            user.setHeadImgUrl(headImgUrl);
            user.setLastLoginIp(ip);
            userService.save(user);
        }
        else
        {
            user.setNickname(nickname);
            user.setHeadImgUrl(headImgUrl);
            user.setLastLoginIp(ip);
            userService.update(user);
        }
        
        String sessionKey = jo.getString("session_key");
        String thirdSessionId = MathUtils.uuid();
        String thirdSessionKey = openid + ":" + sessionKey;
        Ehcache cache = cacheManager.getEhcache(User.SESSION_CACHE_NAME);
        cache.put(new Element(thirdSessionId, thirdSessionKey));
        
        return AjaxMsg.success(thirdSessionId);
    }
    
    /**
     * @Title: getAccessToken
     * @Description: TODO(获取token)
     * @param @param appindex
     * @param @param refresh
     * @param @return 设定文件
     * @return String 返回类型
     * @throws
     */
    @RequestMapping(value = "/app/wx/getAccessToken", method = RequestMethod.GET)
    @ResponseBody
    public String getAccessToken(Boolean refresh)
    {
        WxApp wxApp = wxAppService.find(1L);
        
        if (wxApp == null)
        {
            return new AjaxMsg(false, "请在数据库配置公众号").toString();
        }
        
        wxAppService.getAccessToken(wxApp, refresh);
        JSONObject json = new JSONObject();
        json.put("access_token", wxApp.getAccessToken());
        json.put("expires_in", wxApp.getTokenExpiresin());
        
        return new AjaxMsg(true, json).toString();
    }
    
    @RequestMapping(value = "/authorization", method = RequestMethod.GET)
    @ResponseBody
    public String authorization()
    {
        User user = userService.find(13L);
        String sessionKey = "session_key";
        String thirdSessionId = MathUtils.uuid();
        String thirdSessionKey = user.getOpenid() + ":" + sessionKey;
        Ehcache cache = cacheManager.getEhcache(User.SESSION_CACHE_NAME);
        cache.put(new Element(thirdSessionId, thirdSessionKey));
        
        return AjaxMsg.success(thirdSessionId);
    }
}
